package com.app.oasystem.service.impl;


import com.app.oasystem.dto.PageGridDto;
import com.app.oasystem.dto.TableDto;
import com.app.oasystem.entity.User;
import com.app.oasystem.exception.CommonException;
import com.app.oasystem.mapper.UserMapper;
import com.app.oasystem.service.UserService;
import com.app.oasystem.utils.TableDtoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 86+
 * @data 2021-04-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    UserMapper userMapper;


    /**
     * 获取管理用户信息
     *
     * @return List<User>
     */
    @Override
    public List<User> getAdminList() {
        return userMapper.selectList(new QueryWrapper<User>().select("Id","username").eq("role", 0));
    }

    /**
     * 获取用户信息
     *
     * @return User
     */
    @Override
    public User getUserInfo(Integer id) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("Id", id));
    }

    @Override
    public int update(User user) {
        return userMapper.update(user, new UpdateWrapper<User>().eq("username", user.getUsername()));
    }

    @Override
    public int insert(User user) {
        user.setLoginTime(new Date());
        return userMapper.insert(user);
    }

    @Override
    public int delUser(Integer uesrId) {
        return userMapper.deleteById(uesrId);
    }

    @Override
    public TableDto getUserList(PageGridDto pageGridDto) {
        log.error("分页参数信息【{" + pageGridDto + "}】");
        Page<User> page = new Page<>(pageGridDto.getPage(), pageGridDto.getlimit());
        Page selectPage = null;
        if (pageGridDto.getSearchCondition().size() != 0) {
            selectPage = userMapper.selectPage(page, new QueryWrapper<User>().like("username", pageGridDto.getSearchCondition().get("search")).orderByDesc("loginTime"));
        } else {
            selectPage = userMapper.selectPage(page, new QueryWrapper<User>().orderByDesc("loginTime"));
        }
        return TableDtoUtils.setTableDto(selectPage.getTotal(), selectPage.getRecords());
    }

    @Override
    public List<User> getUserList() {
        List<User> users = userMapper.selectList(new QueryWrapper<User>());
        if (null == users || users.size() == 0){
            log.error("当前系统没有用户，请联系管理者添加用户...");
            return null;
        }
        return users;
    }
}
